#include "jsystem.h"
#include <QTECore/jmodule.h>
#include <QTECore/jlog.h>
#include <QDateTime>
#include <QThread>
#include <cstdlib>

#if defined(Q_OS_WIN32) || defined(Q_OS_WIN64) || defined(Q_OS_WINRT)
# include <windows.h>
#endif

namespace QTE
{

QTECORE_EXPORT void setDataTime(const QDateTime &dt)
{
#if defined(Q_OS_WIN32) || defined(Q_OS_WIN64) || defined(Q_OS_WINRT)

	SYSTEMTIME time;

	time.wYear         = dt.date().year();
	time.wMonth        = dt.date().month();
	time.wDay          = dt.date().day();
	time.wHour         = dt.time().hour();
	time.wMinute       = dt.time().minute();
	time.wSecond       = dt.time().second();
	time.wMilliseconds = dt.time().msec();

	BOOL res = SetLocalTime(&time);

#else

# if defined(Q_OS_UNIX) || defined(Q_OS_LINUX)
	QString cmd = "date -s " + dt.toString("yyyy.MM.dd-hh:mm:ss");
# elif defined(Q_OS_MAC32) || defined(Q_OS_MAC64) || defined(Q_OS_MACX) || defined(Q_OS_OSX)
	QString cmd = "";
# else
#  error *** Do not know the 'set time' command.
# endif

	int res = ::system(cmd.toStdString().c_str());

#endif

	Q_UNUSED(res);
}

[[noreturn]] QTECORE_EXPORT void shutdown() noexcept
{
	QTE_exit_run(0);

#if defined(Q_OS_UNIX) || defined(Q_OS_LINUX)
	const char *cmd = "shutdown now";
#elif defined(Q_OS_WIN32) || defined(Q_OS_WIN64) || defined(Q_OS_WINRT)
	const char *cmd = "shutdown /s /t 0";
#elif defined(Q_OS_MAC32) || defined(Q_OS_MAC64) || defined(Q_OS_MACX) || defined(Q_OS_OSX)
	const char *cmd = "shutdown -h now";
#else
# error *** Do not know the shutdown command.
#endif

	for(;;)
	{
		jInfo() << "system shutdonw...";

		int res = ::system(cmd);
		Q_UNUSED(res);

		QThread::msleep(500);
	}
}

[[noreturn]] QTECORE_EXPORT void reboot() noexcept
{
	QTE_exit_run(0);

#if defined(Q_OS_UNIX) || defined(Q_OS_LINUX) || defined(Q_OS_MAC32) || \
	defined(Q_OS_MAC64) || defined(Q_OS_MACX) || defined(Q_OS_OSX)
	const char *cmd = "reboot";
#elif defined(Q_OS_WIN32) || defined(Q_OS_WIN64) || defined(Q_OS_WINRT)
	const char *cmd = "shutdown /r /t 0";
#else
# error *** Do not know the shutdown command.
#endif

	for(;;)
	{
		jInfo() << "system restart...";

		int res = ::system(cmd);
		Q_UNUSED(res);

		QThread::msleep(500);
	}
}

} //namespace QTE
